package com.ys.utils.annotation.aop;

import com.ys.utils.annotation.RiskValidation;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.spring.config.SystemError;
import com.ys.web.user.risk.Risk;
import com.ys.web.user.risk.RiskMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 风控aop拦截器
 */
@Aspect
@Component
public class RiskValidationContract {
	@Autowired
	private RiskMapper riskMapper;

    /**
     * 定义一个切入点,所有注解了Redis的方法或类
     */
    @Pointcut("@annotation(com.ys.utils.annotation.RiskValidation)")
    private void anyMethod(){

    }

    @Before("anyMethod() && @annotation(anno)")
    public void getRedisData(JoinPoint joinPoint, RiskValidation anno) {
		long uid = getUid(joinPoint);;
		Risk risk = riskMapper.selectByUserId(uid);
		if(uid==0 || StringHandler.isNotEmpty(risk)){
			SystemError.wrapBs("500","账号异常，请联系客服");
		}
		// 验证 公司账号被风控
//		String methodName = ((MethodSignature) joinPoint.getSignature()).getMethod().getName();
//		if(methodName.equals("rechargeCreate") && RiskManager.contains(StringHandler.getLong(Config.pp.get("wallet.withholding.fee.user.id")))){
//			SystemError.wrapBs("500","账号异常，请联系客服.");
//		}
//		if(methodName.equals("popularizeWithoding") && RiskManager.contains(StringHandler.getLong(Config.pp.get("wallet.withholding.group.money.user.id")))){
//			SystemError.wrapBs("500","账号异常，请联系客服..");
//		}
    }

	/**
	 * 获取sysId
	 * @param joinPoint
	 * @return
	 */
	private long getUid(JoinPoint joinPoint){
		DefaultParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer();
		MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
		String[] paramNames = nameDiscoverer.getParameterNames(methodSignature.getMethod());
		Object[] args = joinPoint.getArgs();
		long uid = 0;
		for(int i = 0 ; i < args.length ; i++) {
			if(Objects.requireNonNull(paramNames)[i].equals("uid")){
				uid = StringHandler.getLong(args[i]);
			}
		}
		return uid;
	}
}
